package org.example.hashAndSet;

import java.util.HashMap;

public class Code03_CopyListWithRandom {
    public static class Node {
        public int value;
        public Node next;
        public Node random;
        public Node(int value) {
            this.value = value;
        }
    }

    public static Node copyListWithRandom1(Node head) {
        HashMap<Node ,Node> map = new HashMap<>();
        Node cur = head;
        while (cur != null) {
            map.put(cur,new Node(cur.value));
            cur = cur.next;
        }
        cur = head;
        while (cur!= null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }
    public static Node copyListWithRandom2(Node head) {
        if(head == null) {
            return null;
        }
        Node cur = head;
        Node next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = new Node(cur.value);
            cur.next.next = next;
            cur = next;
        }
        cur = head;
        Node curCopy = null;
        while (cur != null) {
            next = cur.next.next;
            curCopy = cur.next;
            curCopy.random = cur.random != null ? cur.random.next : null;
            cur = next;
        }
        Node res = head.next;
        cur = head;
        while (cur != null) {
            next = cur.next.next;
            curCopy = cur.next;
            cur.next = next;
            curCopy.next = next != null ? next.next : null;
            cur = next;
        }
        return res;
    }
}
